/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.javacommunity.model.dao.impl;

import com.javacommunity.hibernate.HibernateUtil;
import com.javacommunity.model.dao.CategoryTypeDAO;
import com.javacommunity.model.entity.CategoryType;
import com.javacommunity.model.entity.CategoryType;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Cong Pham Dinh
 */
public class CategoryTypeDAOImpl implements CategoryTypeDAO{

    private static CategoryTypeDAOImpl categoryTypeDAO;

    public static CategoryTypeDAOImpl getInstance() {
        if (categoryTypeDAO == null) {
            categoryTypeDAO = new CategoryTypeDAOImpl();
        }
        return categoryTypeDAO;
    }

    private Session session;
    private Transaction ts;

    @Override
    public CategoryType getCategoryTypeById(int categoryTypeId) {
        session = HibernateUtil.getSessionFactory().openSession();
        CategoryType categoryType = null;
        try {
            ts = session.beginTransaction();
            categoryType = (CategoryType) session.get(CategoryType.class, categoryTypeId);
            ts.commit();
        } catch (HibernateException e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
        }finally{
            session.close();
        }
        return categoryType;
    }

    @SuppressWarnings("unchecked")
	@Override
    public List<CategoryType> getCategoryTypes() {
        session = HibernateUtil.getSessionFactory().openSession();
        List<CategoryType> categoryTypes = null;
        try {
            ts = session.beginTransaction();
            String sql = "FROM CategoryType";
            Query query = session.createQuery(sql);
            categoryTypes = query.list();
            ts.commit();
        } catch (HibernateException e) {
            if (ts != null) {
                ts.rollback();
            }
            e.printStackTrace();
        }finally{
            session.close();
        }
        return categoryTypes;
    }
    
}
